package fragments;

import java.io.File;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

import com.yandex.yandexfotki.R;
import com.yandex.yandexfotki.activities.StartActivity;

public class TakePhotoFragment extends Fragment {

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(imageUri !=null) {
			Log.d("yandex",imageUri.toString());
			((StartActivity)getActivity()).startPhotoPreview(imageUri);
			imageUri = null;
		}
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.start, container,false);
		initViews(v);
		return v;
	}
	
	private void initViews(View v) {
		Button from_camera = (Button)v.findViewById(R.id.from_camera);
		
		from_camera.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				clickOnFromCamera();
			}
		});
		
		Button from_gallery = (Button)v.findViewById(R.id.from_gallery);
		from_gallery.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				clickOnFromGallery();
			}
		});
	}
	
	private void clickOnFromGallery() {
		Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
		photoPickerIntent.setType("image/*");
		startActivityForResult(photoPickerIntent, 1);
	}
	
	private void clickOnFromCamera() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File file = new File(Environment.getExternalStorageDirectory(), "test.jpg");
		imageUri = Uri.fromFile(file);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intent, 2);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == getActivity().RESULT_OK) {
			if(requestCode == 1) {
				imageUri = data.getData();
				
//		        Bitmap bitmap;
				//try {
				//	bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
//					File image = new File(((StartActivity)getActivity()).getPath(imageUri));
//					((StartActivity)getActivity()).uploadPhoto(image);
//				} catch (FileNotFoundException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				} catch (IOException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
				
			}
		}
	}

	private Uri outputFileUri;
	Uri imageUri;
}
